package com.ctrip.ec.api.admin.controller.order;

import com.ctrip.ec.api.admin.common.ValidateException;
import com.ctrip.ec.api.admin.model.order.OrderDeliverModel;
import com.ctrip.ec.api.admin.model.order.OrderDetailModel;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.member.MemberDao;
import com.ctrip.ec.biz.dao.order.OrderDiscountDao;
import com.ctrip.ec.biz.dao.order.OrderGoodsDao;
import com.ctrip.ec.biz.dao.payment.PaymentDao;
import com.ctrip.ec.biz.dao.user.UserDao;
import com.ctrip.ec.biz.entity.member.MemberEntity;
import com.ctrip.ec.biz.entity.order.OrderDiscountEntity;
import com.ctrip.ec.biz.entity.order.OrderGoodsEntity;
import com.ctrip.ec.biz.entity.order.OrderStatus;
import com.ctrip.ec.biz.entity.payment.PaymentEntity;
import com.ctrip.ec.biz.entity.role.SysRole;
import com.ctrip.ec.dal.EntityBase;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.biz.dao.order.OrderDao;
import com.ctrip.ec.biz.entity.order.OrderEntity;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderDao order;

    @Autowired
    private UserDao user;

    @Autowired
    private OrderGoodsDao orderGoods;

    @Autowired
    private OrderDiscountDao orderDiscount;

    @Autowired
    private MemberDao member;

    @Autowired
    private PaymentDao payment;

    @PostMapping("list")
    public List<OrderDetailModel> list(@RequestBody QueryModel model,
                                       @RequestParam(required = false) String goodsName,
                                       @RequestParam(required = false) Boolean isMiniApp) throws SQLException {
        PagerSetting setting = model.build();
        Long storeId = RequestContext.getStoreId();
        List<Long> roleIds = user.roleIds(RequestContext.getUserId());

        if (!Strings.isNullOrEmpty(goodsName)) {
            String w = "id in (select order_id from " + EntityBase.getTableName(OrderGoodsEntity.class)
                    + " where goods_name like '%" + goodsName + "%' or goods_sn like '%" + goodsName + "%')";
            setting.appendWhere(w);
        }

        if (roleIds.contains(SysRole.superadmin.getId()) == false) {
            if (storeId != null && storeId != 0) {
                setting.appendWhere("store_id=" + storeId);
            }
        }

        if (isMiniApp != null && isMiniApp == true) { //查询小程序订单
            setting.appendWhere("agent_id>0");
        } else {
            setting.appendWhere("agent_id = " + RequestContext.getAgentId());
        }


        List<OrderEntity> list = order.list(setting);
        List<OrderGoodsEntity> goodsList = orderGoods.listByOrderId(list.stream().map(t -> t.getId()).collect(Collectors.toList()));
        List<PaymentEntity> paymentList = payment.listByIds(list.stream().map(t -> t.getPaymentId()).collect(Collectors.toList()));
        List<OrderDetailModel> modelList = new ArrayList<>();
        for (OrderEntity orderEntity : list) {
            OrderDetailModel orderDetailModel = new OrderDetailModel(orderEntity);
            List<OrderGoodsEntity> tmp = goodsList.stream().filter(t -> t.getOrderId().equals(orderDetailModel.getId())).collect(Collectors.toList());
            orderDetailModel.setGoodsList(tmp);
            orderDetailModel.setPaymentName(paymentList.stream().filter(t -> t.getId().equals(orderEntity.getPaymentId())).findFirst().get().getName());
            modelList.add(orderDetailModel);
        }

        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return modelList;
    }

    @PostMapping("miniAppList")
    public List<OrderDetailModel> miniApplist(@RequestBody QueryModel model, @RequestParam(required = false) String goodsName) throws SQLException {
        return this.list(model, goodsName, true);
    }

    @GetMapping("detail/{id}")
    public OrderDetailModel detail(@PathVariable Long id) throws SQLException {
        OrderEntity entity = order.entity(id);
        MemberEntity memberEntity = member.entity(entity.getMemberId());

        OrderDetailModel model = new OrderDetailModel(entity);
        List<OrderGoodsEntity> goodsList = orderGoods.listByOrderId(id);
        model.setGoodsList(goodsList);
        return model;
    }

    @PostMapping("deliver")
    public void deliver(@RequestBody OrderDeliverModel model) throws SQLException {
        if (model.getOrderGoodsIds() == null) { //全部更新
            List<OrderGoodsEntity> orderGoodsList = orderGoods.listByOrderId(model.getId());
            for (OrderGoodsEntity orderGoodsEntity : orderGoodsList) {
                orderGoodsEntity.setShippingCode(model.getShippingCode());
                orderGoodsEntity.setShippingName(model.getShippingName());
                orderGoods.save(orderGoodsEntity);
            }

        } else {
            if (model.getOrderGoodsIds().size() == 0) {
                throw new ValidateException("请选择具体商品发货");
            } else {
                for (Long orderGoodsId : model.getOrderGoodsIds()) {
                    OrderGoodsEntity orderGoodsEntity = orderGoods.entity(orderGoodsId);
                    if (orderGoodsEntity != null) {
                        orderGoodsEntity.setShippingCode(model.getShippingCode());
                        orderGoodsEntity.setShippingName(model.getShippingName());
                        orderGoods.save(orderGoodsEntity);
                    }
                }
            }
        }
        OrderEntity orderEntity = order.entity(model.getId());
        orderEntity.setShippingCode(model.getShippingCode());
        orderEntity.setShippingName(model.getShippingName());
        orderEntity.setShippingTime(new Timestamp(System.currentTimeMillis()));
        orderEntity.setOrderStatus(OrderStatus.已发货.getId());

        order.save(orderEntity);
        //更新发货状态
        //order.updateStatus(OrderStatus.已发货,model.getId());
    }

    @PostMapping("modifyDiscount")
    public void modifyDiscount(@RequestBody OrderEntity entity) throws SQLException {
        BigDecimal discount = entity.getDiscount();

        OrderEntity oldEntity = order.entity(entity.getId());
        if (oldEntity.getOrderStatus() != OrderStatus.待支付.getId()) {
            throw new ValidateException("现订单状态不能修改");
        }

        OrderDiscountEntity discountEntity = new OrderDiscountEntity();
        discountEntity.setCreateId(RequestContext.getUserId());
        discountEntity.setCreateName(RequestContext.getUserName());
        discountEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        discountEntity.setDicount(entity.getDiscount());
        discountEntity.setOrderId(entity.getId());
        orderDiscount.save(discountEntity);

        oldEntity.setDiscount(discount);
        //payment_amount= goods_amount+shipping_amount-coupon_amount-discount

        BigDecimal paymentAmount = oldEntity.getGoodsAmount().add(oldEntity.getShippingAmount()).subtract(discount);
        if (oldEntity.getCouponAmount() != null) {
            paymentAmount = paymentAmount.subtract(oldEntity.getCouponAmount());
        }

        oldEntity.setPaymentAmount(paymentAmount);
        order.save(oldEntity);


    }

    @PostMapping("save")
    public Long save(@RequestBody OrderEntity entity) throws SQLException {
        order.save(entity);
        return entity.getId();
    }

    @PostMapping("delete")
    public void delete(@RequestBody List<Long> ids) throws SQLException {
        order.delete(ids);
    }

    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws SQLException {
        order.erase(ids);
    }

    @PostMapping("unerase")
    public void unerase(@RequestBody List<Long> ids) throws SQLException {
        order.unerase(ids);
    }
}
